/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState } from "react";
import { useMount, useFormTable } from "@umijs/hooks";
import { connect } from "dva";
import PageHeaderLayout from "@/layouts/PageHeaderLayout";
import { Button, Form, Input, Popconfirm, Modal } from "antd";
import StandardTable from "@/components/StandardTable";
import { debounce } from "lodash";
import DerivativeModal from "./DerivativeModal";
import styles from "../style.less";

const { confirm } = Modal;

const DerivativeManage = props => {
  const {
    form: { getFieldDecorator, validateFields },
    dispatch,
    derivativeManage: { derivativeManageList },
    cascaderInfo,
    form,
  } = props;
  const [visibleModal, setVisibleModal] = useState(false);
  const [titleModal, setTitleModal] = useState("添加微商");
  const [typeModal, setTypeModal] = useState("add");
  const [selectedRecord, setSelectedRecord] = useState();
  const [selectedRows, setSelectedRows] = useState([]);
  const [modalFormValues, setMoadlFormValues] = useState({});
  const [shopIdGroup, setShopIdGroup] = useState({
    id: "",
    kb_id: "",
  });
  const { loading, search } = useFormTable(getDerivativeManagementByUseFormTable, {
    defaultPageSize: 5,
    form,
  });
  function getDerivativeManagementByUseFormTable(tableParam, formData) {
    return getDerivativeManagement({ ...tableParam, ...formData });
  }
  function getDerivativeManagement(data) {
    return dispatch({
      type: "derivativeManage/getDerivativeManagement",
      payload: {
        ...data,
      },
    });
  }
  useMount(() => {
    dispatch({
      type: "clientManage/getCascaderInfo",
    });
  });
  const onDelet = (id, tip) => {
    confirm({
      title: tip,
      onOk() {
        tableFooterConfirm(id);
      },
      onCancel() {},
      okText: "确认",
      cancelText: "取消",
    });
  };
  const tableFooterConfirm = id => {
    dispatch({
      type: "derivativeManage/deleteDerivativeInfo",
      payload: { id },
    }).then(res => {
      getFormValues(getDerivativeManagement);
    });
  };
  const { submit } = search;
  const tableFooter = {
    name: "footer",
    component: props => {
      const { selectedRows } = props;
      const courier_names = selectedRows
        .filter((_, i) => i <= 4)
        .map((val, i) => {
          if (i < 3) {
            return val.courier_name;
          } else {
            return "等...";
          }
        })
        .join(",");
      const id = selectedRows.map(val => val.id).join(",");
      const tip = `删除数据后此微商客户将无法选择同步订单至绑定的${courier_names}业务员了，请确认是否删除`;
      return (
        <Button type="primary" onClick={() => onDelet(id, tip)}>
          删除
        </Button>
      );
    },
  };
  const columns = [
    {
      title: "店铺名称",
      key: "shop_name",
      dataIndex: "shop_name",
      align: "center",
    },
    {
      title: "店铺电话",
      key: "phone",
      dataIndex: "phone",
      align: "center",
    },
    {
      title: "业务员",
      key: "courier_name",
      dataIndex: "courier_name",
      align: "center",
      render(value, record) {
        return `${value}-${record.courier_phone}`;
      },
    },
    {
      title: "操作",
      align: "center",
      render: (text, record) => {
        return <a onClick={() => onTriggerModal("edit", record)}>编辑</a>;
      },
    },
  ];

  const onSelectRowHandleDel = () => {};
  const handelPhoneBlur = values => {
    const { phone } = values;
    return dispatch({
      type: "derivativeManage/wsSearchPhone",
      payload: { phone },
    }).then(res => {
      const { shop_name, id, kb_id } = res;
      setShopIdGroup({ id, kb_id });
      setMoadlFormValues({ shop_name });
    });
  };
  const handleTableChange = debounce(
    pagination => {
      form.validateFields((err, filedVlue) => {
        if (err) return;
        dispatch({
          type: "derivativeManage/getDerivativeManagement",
          payload: {
            ...filedVlue,
            size: 100,
            page: pagination.current,
          },
        });
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    }
  );
  const handleModalOk = data => {
    setVisibleModal(false);
    // 判断是否是新增还是修改
    let type;
    let params = {
      courier_phone: data.courier_no[1],
      shop_name: data.shop_name,
      phone: data.phone,
    };
    if (data.type == "add") {
      params = { ...params, ...shopIdGroup };
      type = "derivativeManage/addDerivativeInfo";
    } else {
      type = "derivativeManage/editDerivativeInfo";
      params.id = data.record.id;
    }
    dispatch({
      type,
      payload: {
        ...params,
      },
    }).then(() => {
      getFormValues(getDerivativeManagement);
    });
  };
  const onTriggerModal = (type, record) => {
    let title;
    switch (type) {
      case "add":
        title = "添加微商";
        break;
      case "edit":
        title = "编辑微商信息";
        setMoadlFormValues({
          courier_no: [record.company_site_id, record.courier_phone],
        });
        break;
      default:
        break;
    }
    setTitleModal(title);
    setTypeModal(type);
    record && setSelectedRecord(record);
    setVisibleModal(true);
  };
  const getFormValues = then => {
    validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      values.page = 1;
      values.size = 100;
      then(values);
    });
  };

  return (
    <div>
      <div style={{ position: "relative" }}>
        <Form layout="inline" style={{ marginBottom: 24 }}>
          <Form.Item>
            {getFieldDecorator("shop_search")(
              <Input style={{ width: 300 }} placeholder="可根据店铺名称、联系人或绑定手机号搜索" />
            )}
          </Form.Item>
          <Form.Item>
            {getFieldDecorator("courier_search")(
              <Input style={{ width: 300 }} placeholder="可根据业务员手机号、或者姓名搜索" />
            )}
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              icon="search"
              htmlType="submit"
              loading={loading}
              onClick={submit}
            >
              查询
            </Button>
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={() => onTriggerModal("add")}>
              添加微商
            </Button>
          </Form.Item>
        </Form>

        <StandardTable
          rowKey={record => record.id}
          columns={columns}
          data={derivativeManageList}
          loading={loading}
          selectedRows={selectedRows}
          footer={tableFooter}
          onSelectRowHandle={onSelectRowHandleDel}
          // onSelectRow={onRowSelect}
          onChange={handleTableChange}
        />
      </div>
      <DerivativeModal
        title={titleModal}
        type={typeModal}
        visible={visibleModal}
        cascaderInfo={cascaderInfo}
        onPhoneBlur={handelPhoneBlur}
        onOk={handleModalOk}
        onCancel={() => setVisibleModal(false)}
        record={selectedRecord}
        formValuse={modalFormValues}
      />
    </div>
  );
};

export default connect(({ derivativeManage, clientManage }) => ({
  derivativeManage,
  cascaderInfo: clientManage.cascaderInfo,
}))(Form.create()(DerivativeManage));
